package com.lishe.lishe.lishe.module.mall.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.HttpUtils;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshHeaderLayout;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseFragment;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.adapter.ImageViewPagerAdapter;
import com.lishe.lishe.lishe.module.mall.adapter.MallAllGoodsBaseAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.category.Category;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.LinkedList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lwa on 2017/9/21.
 * 商城-全部
 */

public class MallAllGoodsFragment extends BaseFragment {

    private Category category;
    private LinkedList<MallGoods> mallGoods = new LinkedList<>();//列表显示的商品
    private LinkedList<MallGoods> mallGoodsHost = new LinkedList<>();//热点横向显示的商品
    private RefreshRecyclerView recycleView;
    private MallAllGoodsBaseAdapter mallAllGoodsAdapter;
    private ImageLoaderUtils imageLoaderUtils;

    //-----------------------------headerView---------------------------
    private LinkedList<ImageView> imageViews = new LinkedList<>();//轮播的图片
    private LinkedList<View> points = new LinkedList<>();//轮播的图片的小圆点

    private int pageIndex = 0;
    private int oldIndex = 0;

    private RelativeLayout empty;
    private TextView emptyText;

    public static MallAllGoodsFragment newInstance(Category category) {
        MallAllGoodsFragment fragment = new MallAllGoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("category", category);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        category = (Category) getArguments().getSerializable("category");
        imageLoaderUtils = new ImageLoaderUtils();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mall_all_fregment, null);
        mallAllGoodsAdapter = new MallAllGoodsBaseAdapter(getActivity(), mallGoods);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View view) {
        empty = view.findViewById(R.id.empty);
        emptyText = view.findViewById(R.id.text);
        recycleView = view.findViewById(R.id.recycleView);
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.setOnItemClickListener(new RefreshRecyclerView.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                //item主图的点击事件，滚动栏点击在adapter中实现
                MallGoods mall = mallGoods.get(position);
                MallGoodsActivity.jump(getActivity(), mall.getItem_id());
            }
        });

        recycleView.setOnRefreshListener(new RecyclerViewRefreshListener() {
            @Override
            public void onHeaderRefresh(View headerView) {
                String label = new Date().toLocaleString();
                ((RefreshHeaderLayout)headerView).setLable(label);
                getData();
            }

            @Override
            public void onFooterRefresh(View footerViwe) {

            }
        });
        recycleView.setAdapter(mallAllGoodsAdapter);
        recycleView.setRefreshing();
        emptyText.setText("加载中...");
        if (mallGoods.size() == 0) {
            empty.setVisibility(View.VISIBLE);
        } else {
            empty.setVisibility(View.GONE);
        }
    }

    private void getData() {
        if (category != null) {
            HttpUtils.get(category.getUrl(), null, goodsDataResposetType1);
        }
    }

    AsyncHttpResponseHandler goodsDataResposetType1 = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            LoadingUtils.closeDialog();
            String result = new String(responseBody);
            Log.e("商品全部result", result);
            recycleView.setCompleteRefresh();
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray bannerList = data.optJSONArray("bannerList");
                    JSONArray floors = data.optJSONArray("floors");
                    mallGoods.clear();
                    mallGoodsHost.clear();
                    for (int i = 0; i < bannerList.length(); i++) {//hear轮播的数据
                        MallGoods mallGood = new MallGoods();
                        JSONObject object = bannerList.optJSONObject(i);
                        mallGood.setImage_default_id(object.optString("banner_img"));
                        mallGood.setItem_id(object.optString("item_id"));
                        mallGoodsHost.add(mallGood);
                    }
                    for (int i = 0; i < floors.length(); i++) {
                        MallGoods mallGood = new MallGoods();
                        JSONObject object = floors.optJSONObject(i);
                        mallGood.setImage_default_id(object.optString("icon"));
                        mallGood.setItem_id(object.optString("item_id"));
                        JSONArray items = object.optJSONArray("items");
                        mallGood.getItems().clear();
                        for (int j = 0; j < items.length(); j++) {
                            MallGoods itemMallGood = new MallGoods();
                            JSONObject itemObject = items.optJSONObject(j);
                            itemMallGood = JSON.parseObject(itemObject.toString(), MallGoods.class);
                            mallGood.getItems().add(itemMallGood);
                        }
                        mallGoods.add(mallGood);
                    }
                    Log.e("长度", mallGoods.size() + "");
                    mallAllGoodsAdapter.addHeaderView(initHeaderView());
                    mallAllGoodsAdapter.notifyDataSetChanged();
                    if (mallGoods.size() == 0) {
                        empty.setVisibility(View.VISIBLE);
                        emptyText.setText("没有商品，点击刷新！");
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                } else {
                    toast(result);
                    if (mallGoods.size() == 0) {
                        empty.setVisibility(View.VISIBLE);
                        emptyText.setText("没有商品，点击刷新！");
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (mallGoods.size() == 0) {
                    empty.setVisibility(View.VISIBLE);
                    emptyText.setText("没有商品，点击刷新！");
                } else {
                    empty.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            recycleView.setCompleteRefresh();
            LoadingUtils.closeDialog();
            toast("网络或服务器异常！");
            if (mallGoods.size() == 0) {
                empty.setVisibility(View.VISIBLE);
                emptyText.setText("没有商品，点击刷新！");
            } else {
                empty.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 滚动栏的head
     */
    private ImageViewPagerAdapter viewPagerAdapter;
    ViewPager viewPager;

    private View initHeaderView() {
        pageIndex = 0;
        oldIndex = 0;
        if (viewPagerAdapter == null) {
            viewPagerAdapter = new ImageViewPagerAdapter(imageViews);
        }
        View v = getActivity().getLayoutInflater().inflate(R.layout.item_mall_all_header, null, false);
        ViewGroup pa = (ViewGroup) v.getParent();
        if (pa != null) {
            pa.removeAllViews();
        }
        viewPager = v.findViewById(R.id.view_pager);
        viewPager.setAdapter(viewPagerAdapter);
        LinearLayout pointLayout = v.findViewById(R.id.point_layout);
        pointLayout.removeAllViews();
        points.clear();
        imageViews.clear();
        for (final MallGoods url : mallGoodsHost) {
            //图片
            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageLoaderUtils.displayImage(url.getImage_default_id(), imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MallGoodsActivity.jump(getActivity(), url.getItem_id());
                }
            });
            imageViews.add(imageView);
            //小圆点
            View pointView = getActivity().getLayoutInflater().inflate(R.layout.item_carousel_point, null);
            View point = pointView.findViewById(R.id.point);
            pointLayout.addView(pointView);
            points.add(point);
        }
        viewPager.setCurrentItem(0);
        if (points.size() > 0) {
            points.get(0).setBackgroundResource(R.drawable.shape_red50px);
        }
        viewPagerAdapter.notifyDataSetChanged();
        setOnlistener(viewPager);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 3000);
        return v;
    }

    private void setOnlistener(final ViewPager viewPager) {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (points.size() > oldIndex) {
                    points.get(oldIndex).setBackgroundResource(R.drawable.shape_coner50px);
                }
                if (points.size() > position) {
                    points.get(position).setBackgroundResource(R.drawable.shape_red50px);
                }
                pageIndex = position;
                oldIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //-------------------------轮播图小圆点变化控制--------------
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (pageIndex < mallGoodsHost.size() - 1) {
                pageIndex += 1;
            } else {
                pageIndex = 0;
            }
            viewPager.setCurrentItem(pageIndex, false);
//            mallAllGoodsAdapter.notifyDataSetChanged();
            handler.postDelayed(this, 3000);
        }
    };

}
